package com.atom.module.document.ui;

import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.atom.module.document.Document;
import com.atom.module.document.R;
import com.atom.module.document.helper.BitmapHelper;
import com.atom.module.document.helper.PointHelper;
import com.atom.module.document.utils.DocumentUtils;
import com.atom.module.document.view.CropView;
import com.atom.module.document.view.banner.NumIndicator;
import com.atom.module.logger.Logger;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerAdapter;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.listener.OnPageChangeListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.internal.observers.BlockingBaseObserver;

/**
 * All rights Reserved, Designed By www.rongdasoft.com
 *
 * @version V1.0
 * @Title: SingleHandleActivity
 * @Description:
 * @author: wuyongzheng
 * @date: 2022/3/28
 * @Copyright: 2022/3/28 www.rongdasoft.com Inc. All rights reserved.
 */
public class MoreHandleOnlyShearAndRotateActivity extends AbstractAppCompatActivity {

    private final List<Document.Entry> entryList = new ArrayList<>();

    private final DocumentBannerAdapter documentAdapter = new DocumentBannerAdapter();

    private void initParams() {
        List<Document.Entry> document = Document.getDocument();
        for (Document.Entry entry : document) {
            if (entry == Document.Entry.EMPTY) continue;
            entryList.add(new Document.Entry(entry));
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initParams();
        setContentView(R.layout.activity_more_handle_only_shear_rotate);
        // 照片预览
        view(R.id.autoDocumentViewList, (PickView<Banner<Document.Entry, DocumentBannerAdapter>>) view -> {
            view.setAdapter(documentAdapter, false);
            view.setIndicator(new NumIndicator(this));
            view.addOnPageChangeListener(new OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    Document.Entry data = documentAdapter.getData(position);
                    toggleAutoShear(PointHelper.isFullPoint(data.getParam(), data.getPoints()));
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            view.setIndicatorGravity(IndicatorConfig.Direction.CENTER);
            view.isAutoLoop(false);
            view.post(() -> {
                documentAdapter.setDatas(entryList);
                // 进行更新第一个的状态
                Document.Entry entry = entryList.get(0);
                toggleAutoShear(PointHelper.isFullPoint(entry.getParam(), entry.getPoints()));
            });
        });
        // 左转
        view(R.id.moreTurnLeftLayoutView, v -> v.setOnClickListener(v1 -> setRotate(-90)));
        // 右转
        view(R.id.moreTurnRightLayoutView, v -> v.setOnClickListener(v12 -> setRotate(+90)));
        // 自动识别文档
        view(R.id.moreAutoShearLayoutView, view -> view.setOnClickListener(v -> autoShear()));
        // 完成保存
        view(R.id.finishHandle, view -> {
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    handleFinish();
                }
            });
        });
    }

    private void toggleAutoShear(boolean isFull) {
        view(R.id.moreAutoShearTextView, (PickView<TextView>) v -> {
            v.setText(isFull ? "自动" : "全部");
        });
    }

    public void handleFinish() {
        // 进行保存执行后的bitmap
        List<Document.Entry> document = Document.getDocument();
        document.clear();
        document.addAll(entryList);
        document.add(Document.Entry.EMPTY);
        finish();
    }

    public void setRotate(int rotate) {
        view(R.id.autoDocumentViewList, (PickView<Banner<Document.Entry, DocumentBannerAdapter>>) view -> {
            int currentItem = view.getCurrentItem();
            // 目前的
            Document.Entry currEntry = entryList.get(currentItem);
            Document.Param param = currEntry.getParam();
            int oldBitmapW = param.getWidth();
            int oldBitmapH = param.getHeight();
            currEntry.setRotate(rotate);
            if (currEntry.getPoints() != null) {
                currEntry.setPoints(PointHelper.rotatePoint(oldBitmapW, oldBitmapH, rotate, currEntry.getPoints()));
            }
            documentAdapter.notifyItemChanged(currentItem);
        });
    }

    public void autoShear() {
        view(R.id.autoDocumentViewList, (PickView<Banner<Document.Entry, DocumentBannerAdapter>>) view -> {
            int currentItem = view.getCurrentItem();
            Document.Entry currEntry = entryList.get(currentItem);
            Document.Param param = currEntry.getParam();
            if (!PointHelper.isFullPoint(param, currEntry.getPoints())) {
                currEntry.setPoints(PointHelper.createFullPoint(param));
                documentAdapter.notifyItemChanged(currentItem);
                toggleAutoShear(true);
                return;
            }
            Bitmap rotateBitmap = currEntry.getRotateBitmap();
            DocumentUtils.analysisArray(DocumentUtils.createFrame(rotateBitmap), new BlockingBaseObserver<Point[]>() {
                @Override
                public void onNext(Point[] points) {
                    currEntry.setPoints(points);
                    documentAdapter.notifyItemChanged(currentItem);
                    toggleAutoShear(false);
                    if (!rotateBitmap.isRecycled()) {
                        rotateBitmap.recycle();
                    }
                }

                @Override
                public void onError(Throwable e) {
                    Logger.e(e);
                    if (!rotateBitmap.isRecycled()) {
                        rotateBitmap.recycle();
                    }
                }
            });
        });
    }

    //------------------------------------------------------------------------------

    class DocumentBannerAdapter extends BannerAdapter<Document.Entry, ViewHolder> {

        public DocumentBannerAdapter() {
            super(null);
        }

        @Override
        public int getItemViewType(int position) {
            return R.layout.item_more_view_holder_only_document;
        }

        @Override
        public ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(viewType, parent, false));
        }

        @Override
        public void onBindView(ViewHolder holder, Document.Entry data, int position, int size) {
            holder.onBind(data);
        }
    }

    private final Map<String, Bitmap> bitmapCache = new HashMap<>();

    class ViewHolder extends RecyclerView.ViewHolder {

        private final CropView documentShow;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            documentShow = itemView.findViewById(R.id.documentShow);

        }

        public void onBind(Document.Entry entry) {
            Bitmap bitmap = bitmapCache.get(entry.getSourcePath());
            if (bitmap == null) {
                bitmap = entry.getRotateBitmap();
            } else {
                bitmap = BitmapHelper.rotateBitmap(bitmap, entry.getRotate(), true);
            }
            bitmapCache.put(entry.getSourcePath(), bitmap);
            documentShow.setImageBitmap(bitmap);
            documentShow.setPoints(entry.getPoints());
        }
    }

    @Override
    protected void onDestroy() {
        for (Bitmap value : bitmapCache.values()) {
            if (value != null && !value.isRecycled()) {
                value.recycle();
            }
        }
        bitmapCache.clear();
        super.onDestroy();
    }
}
